local function loadCsv(s)
	local i, j, q, t, r = 1, 1, 0, {}, {}
	while true do
		local b = s:byte(j)
		j = j + 1
		if b == 0x22 then -- 0x22:'"'
			if q ~= 0 then
				q = 3 - q
			elseif i + 1 == j then
				i, q = j, 1
			end
		elseif q ~= 1 and (b == 0x2c or b == 13 or b == 10) or not b then -- 0x2c:','
			if b == 0x2c or i + 1 < j or #t > 0 then
				local c = s:sub(i, j - (q == 2 and s:byte(j - 2) == 0x22 and 3 or 2))
				if q == 2 then
					c = c:gsub('""', '"')
				end
				t[#t + 1] = c
				if b ~= 0x2c then
					r[#r + 1] = t
					t = {}
				end
			end
			if not b then
				return r
			end
			i, q = j, 0
		end
	end
end

local f = io.open("test.csv","rb")
local s = f:read "*a"
f:close()

local r = loadCsv(s) -- loadCsv '\r"""a",a",,"""a""",a"b,\r\n,\r\n \n'
for _, t in ipairs(r) do
	for _, s in ipairs(t) do
		io.write('[', s, '] ')
	end
	print()
end
print("--- " .. #r)
